// app/src/main/java/com/example/yougoumall/ui/fragment/CategoryFragment.java
package com.example.hlddz2.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hlddz2.R;
import com.bumptech.glide.Glide;
import com.example.hlddz2.model.Category;
import com.example.hlddz2.network.ApiService;
import com.example.hlddz2.repository.ProductRepository;
import com.example.hlddz2.viewmodel.CategoryViewModel;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class CategoryFragment extends Fragment {

    private CategoryViewModel viewModel;
    private LeftAdapter leftAdapter;
    private RightAdapter rightAdapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_category, container, false);

        RecyclerView rvLeft = root.findViewById(R.id.rv_left);
        RecyclerView rvRight = root.findViewById(R.id.rv_right);

        rvLeft.setLayoutManager(new LinearLayoutManager(getContext()));
        rvRight.setLayoutManager(new GridLayoutManager(getContext(), 2));

        leftAdapter = new LeftAdapter(new ArrayList<>());
        rightAdapter = new RightAdapter(new ArrayList<>());
        rvLeft.setAdapter(leftAdapter);
        rvRight.setAdapter(rightAdapter);

        // Retrofit for this fragment (simple local provider; could be DI later)
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(logging)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api-hmugo-web.itheima.net/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        ApiService apiService = retrofit.create(ApiService.class);
        ProductRepository repository = new ProductRepository(apiService);
        viewModel = new ViewModelProvider(this, new ViewModelProvider.Factory() {
            @NonNull
            @Override
            public <T extends androidx.lifecycle.ViewModel> T create(@NonNull Class<T> modelClass) {
                return (T) new CategoryViewModel(repository);
            }
        }).get(CategoryViewModel.class);

        viewModel.getTopCategories().observe(getViewLifecycleOwner(), categories -> {
            leftAdapter.setData(categories == null ? new ArrayList<>() : categories);
        });

        viewModel.getSubCategories().observe(getViewLifecycleOwner(), subCats -> {
            rightAdapter.setData(subCats == null ? new ArrayList<>() : subCats);
        });

        leftAdapter.setOnItemClickListener(position -> viewModel.selectCategory(position));

        viewModel.loadCategories();

        return root;
    }

    static class LeftAdapter extends RecyclerView.Adapter<LeftAdapter.VH> {
        private List<Category> data;
        private OnItemClickListener listener;

        LeftAdapter(List<Category> data) {
            this.data = data;
        }

        void setData(List<Category> data) {
            this.data = data;
            notifyDataSetChanged();
        }

        void setOnItemClickListener(OnItemClickListener l) {
            this.listener = l;
        }

        @NonNull
        @Override
        public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_category_left, parent, false);
            return new VH(v);
        }

        @Override
        public void onBindViewHolder(@NonNull VH holder, int position) {
            Category c = data.get(position);
            holder.name.setText(c.getCat_name());
            holder.itemView.setOnClickListener(v -> {
                if (listener != null) listener.onClick(position);
            });
        }

        @Override
        public int getItemCount() {
            return data == null ? 0 : data.size();
        }

        static class VH extends RecyclerView.ViewHolder {
            TextView name;
            VH(@NonNull View itemView) {
                super(itemView);
                name = itemView.findViewById(R.id.tv_left_name);
            }
        }
    }

    static class RightAdapter extends RecyclerView.Adapter<RightAdapter.VH> {
        private List<Category> data;

        RightAdapter(List<Category> data) {
            this.data = data;
        }

        void setData(List<Category> data) {
            this.data = data;
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_category_right, parent, false);
            return new VH(v);
        }

        @Override
        public void onBindViewHolder(@NonNull VH holder, int position) {
            Category c = data.get(position);
            holder.name.setText(c.getCat_name());
            String url = c.getCat_icon();
            if (url != null && !url.isEmpty()) {
                holder.icon.setVisibility(View.VISIBLE);
                Glide.with(holder.itemView.getContext())
                        .load(url)
                        .placeholder(R.color.light_gray)
                        .into(holder.icon);
            } else {
                holder.icon.setVisibility(View.GONE);
            }
        }

        @Override
        public int getItemCount() {
            return data == null ? 0 : data.size();
        }

        static class VH extends RecyclerView.ViewHolder {
            TextView name;
            android.widget.ImageView icon;
            VH(@NonNull View itemView) {
                super(itemView);
                name = itemView.findViewById(R.id.tv_right_name);
                icon = itemView.findViewById(R.id.iv_right_icon);
            }
        }
    }

    interface OnItemClickListener {
        void onClick(int position);
    }
}